package com.linzm.leetcode.mid.tree.层次遍历;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author zimingl
 * @Date 2023/2/20 23:37
 * @Description: 给定一个二叉树的 根节点 root，想象自己站在它的右侧，按照从顶部到底部的顺序，返回从右侧所能看到的节点值。
 * 层次遍历
 */
public class RightSideView199 {
    public static void main(String[] args) {
        RightSideView199 rightSideView199 = new RightSideView199();
        List<Integer> list = rightSideView199.rightSideView3(TreeNode.getTree());
        System.out.println(list);
    }
    // bfs
    public List<Integer> rightSideView2(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            res.add(queue.getLast().val);
            while (len > 0) {
                root = queue.poll();
                if (root.left != null) queue.offer(root.left);
                if (root.right != null) queue.offer(root.right);
                len--;
            }
        }
        return res;
    }

    // dfs
    public List<Integer> rightSideView3(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        List<LinkedList<Integer>> list = new ArrayList<>();
        traverval(root, list, 0);
        for (LinkedList<Integer> linkedList : list) {
            res.add(linkedList.getLast());
        }
        return res;
    }

    private void traverval(TreeNode root, List<LinkedList<Integer>> list, int depth) {
        if (root == null) return;
        depth++;
        if (depth > list.size()) {
            list.add(new LinkedList<>());
        }
        list.get(depth - 1).add(root.val);
        traverval(root.left, list, depth);
        traverval(root.right, list, depth);
    }
}
